package org.grew.openEntity.service.Impl;

import org.grew.openEntity.repository.EditionEntityRepository;
import org.grew.openEntity.repository.EntityRepository;
import org.grew.openEntity.po.logic.ColumnObj;
import org.grew.openEntity.po.logic.EditionEntityObj;
import org.grew.openEntity.po.logic.EntityObj;
import org.grew.openEntity.service.ColumnService;
import org.grew.openEntity.service.EntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

/**
 * @program: open_entity
 * @author: todd
 * @create: 2019-01-05 22:34
 * @description: ${description}
 */
@Service
@Transactional
public class EntityServiceImpl implements EntityService {

    @Autowired
    private EditionEntityRepository editionEntityRepository;

    @Autowired
    private EntityRepository entityRepository;

    @Autowired
    private ColumnService columnService;

    @Override
    public void createEntity(Long editionId, EntityObj entity, List<ColumnObj> columns) {
        EntityObj save = entityRepository.save(entity);
        editionEntityRepository.save(new EditionEntityObj(editionId,save.getId()));
        for (ColumnObj column : columns) {
            columnService.createColumn(column,save.getId());
        }
    }

    @Override
    public void updateEntity(Long editionId, EntityObj entity) {
        EntityObj save = entityRepository.save(entity);
        editionEntityRepository.save(new EditionEntityObj(editionId,save.getId()));
    }

    @Override
    public void deleteEntity(Long id) {
        entityRepository.deleteById(id);
    }

    @Override
    public EntityObj getEntityById(Long id) {
        Optional<EntityObj> byId = entityRepository.findById(id);
        return byId.isPresent()?byId.get():null;
    }

    @Override
    public List<EntityObj> getEntityByName(String entityName) {
        return entityRepository.findEntityObjByEntityName(entityName);
    }

    @Override
    public long getEntityCount() {
        return entityRepository.count();
    }
}
